package servlets.local;

import hibernate.method.RateMethods;
import hibernate.util.HibernateUtil;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 * Servlet implementation class addLocalRate
 */
@WebServlet("/addLocalRate")
public class addLocalRate extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public addLocalRate() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		String local = (String) request.getParameter("local_id");
		String user = (String) request.getParameter("user");
		String rate = (String) request.getParameter("rate");

		int local_id = Integer.parseInt(local);
		int user_id = Integer.parseInt(user);
		int rate1 = Integer.parseInt(rate);

		PrintWriter out = response.getWriter();
		SessionFactory sessionFactory = HibernateUtil
				.getSessionAnnotationFactory();
		Session session = sessionFactory.openSession();
		RateMethods rm = new RateMethods();
		session.beginTransaction();

		if (rm.findLocalRateByUserGame(sessionFactory, session, user_id,
				local_id).isEmpty())
			rm.addLocalRate(sessionFactory, session, user_id, local_id, rate1);
		else
			rm.editLocalRate(
					sessionFactory,
					session,
					rm.findLocalRateByUserGame(sessionFactory, session,
							user_id, local_id).get(0), rate1);

		try {
			session.getTransaction().commit();
			out.println("<script type=\"text/javascript\">alert(\"Ocena zostala dodana pomyslnie\"); window.location.href = \"social/index.jsp?page=main&group=ourLocals\";</script>");
		} catch (Exception e) {
			out.println("<script type=\"text/javascript\">alert(\"Ocena nie zostala dodana\"); window.location.href = \"social/index.jsp?page=main&group=ourLocals\";</script>");
		}
	}

}
